package dao

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	jwt "github.com/e421083458/gin_scaffold/public"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"html"
	"io/ioutil"
	"log"
	"math"
	"net/http"
	"net/url"
	"os"
	"time"
)

// Uuser 会员表
type Uuser struct {
	Id             int             `gorm:"-;primary_key;AUTO_INCREMENT"`
	Unionid        string          `json:"unionid"`
	Openid         string          `json:"openid"`
	Headimgurl     string          `json:"headimgurl"`
	Truename       string          `json:"truename"`
	Userphone      string          `json:"userphone"`
	Password       string          `json:"password"`
	Sex            int             `json:"sex"`
	Birthday       string          `json:"birthday"`
	Height         int             `json:"height"`
	Weight         int             `json:"weight"`
	Blood          string          `json:"blood"`
	Fromuid        int             `json:"fromuid"`
	InviterIds     string          `json:"inviter_ids"`
	GradeId        int             `json:"grade_id"`
	Endtime        int64           `json:"endtime"`
	Times          int             `json:"times"`
	Huid           int             `json:"huid"`
	Lastlogin      string          `json:"lastlogin"`
	Regip          string          `json:"regip"`
	Qr             string          `json:"qr"`
	Money          decimal.Decimal `json:"money"`
	BrokerageMoney decimal.Decimal `json:"brokerage_money"`
	IdCard         string          `json:"id_card"`
	Spouse         int             `json:"spouse"`
	Father         int             `json:"father"`
	Mother         int             `json:"mother"`
	Sfather        int             `json:"sfather"`
	Smother        int             `json:"smother"`
	Child1         int             `json:"child1"`
	Child2         int             `json:"child2"`
	Othier         int             `json:"othier"`
	Level          int             `json:"level"`
	Show           int             `json:"show"`
	FromLevelId    int             `json:"from_level_id"`
}
type Uuser2 struct {
	Id             int             `gorm:"-;primary_key;AUTO_INCREMENT"`
	Unionid        string          `json:"unionid"`
	Openid         string          `json:"openid"`
	Headimgurl     string          `json:"headimgurl"`
	Truename       string          `json:"truename"`
	Userphone      string          `json:"userphone"`
	Password       string          `json:"password"`
	Sex            int             `json:"sex"`
	Birthday       string          `json:"birthday"`
	Height         int             `json:"height"`
	Weight         int             `json:"weight"`
	Blood          string          `json:"blood"`
	Fromuid        int             `json:"fromuid"`
	InviterIds     string          `json:"inviter_ids"`
	GradeId        int             `json:"grade_id"`
	Endtime        int64           `json:"endtime"`
	Times          int             `json:"times"`
	Huid           int             `json:"huid"`
	Lastlogin      string          `json:"lastlogin"`
	Regip          string          `json:"regip"`
	Qr             string          `json:"qr"`
	Money          decimal.Decimal `json:"money"`
	BrokerageMoney decimal.Decimal `json:"brokerage_money"`
	IdCard         string          `json:"id_card"`
	Spouse         int             `json:"spouse"`
	Father         int             `json:"father"`
	Mother         int             `json:"mother"`
	Sfather        int             `json:"sfather"`
	Smother        int             `json:"smother"`
	Child1         int             `json:"child1"`
	Child2         int             `json:"child2"`
	Othier         int             `json:"othier"`
	Level          int             `json:"level"`
	FromLevelId    int             `json:"from_level_id"`
}

// wcode 核销码表
type Wcode struct {
	Id         int    `json:"id"`
	Fid        int    `json:"fid"`
	Ctype      int    `json:"ctype"`
	Tcode      string `json:"tcode"`
	PicAddr    string `json:"pic_addr"`
	Uid        int    `json:"uid"`
	AddTime    int64  `json:"addtime"`
	ActiveTime int64  `json:"active_time"`
	Status     int    `json:"status"`
	Msg        string `json:"msg"`
}

// wcode 核销码表2，查询列表用
type Wcode2 struct {
	Tcode      string `json:"tcode"`
	PicAddr    string `json:"pic_addr"`
	Uid        int    `json:"uid"`
	AddTime    int64  `json:"addtime"`
	ActiveTime int64  `json:"active_time"`
	Status     int    `json:"status"`
}

// Admin 健康管理师
type Admin struct {
	Id         int    `json:"id"`
	Truename   string `json:"truename"`
	Username   string `json:"username"`
	Phone      string `json:"phone"`
	Headimgurl string `json:"headimgurl"`
	Cons       int    `json:"cons"`   //咨询次数
	Praise     int    `json:"praise"` //好评次数
	Context    string `json:"context"`
	Star       string `json:"star"` //星级
	Area       string `json:"area"`
	Url        string `json:"url"`
}

// Pulse 数字脉诊数据
type Pulse struct {
	Id            int   `json:"id"`
	Uid           int   `json:"uid"`
	Leftrate      int   `json:"leftrate"`
	Leftlowpre    int   `json:"leftlowpre"`
	Lefthightpre  int   `json:"lefthightpre"`
	Rightrate     int   `json:"rightrate"`
	Rightlowpre   int   `json:"rightlowpre"`
	Righthightpre int   `json:"righthightpre"`
	Addtime       int64 `json:"addtime"`
	Status        int   `json:"status"`
	Del           int   `json:"del"`
}

// UserWuzhang 五脏
type UserWuzhang struct {
	Id              int    `json:"id"`
	Uid             int    `json:"uid"`
	Pid             int    `json:"pid"`
	Title           string `json:"title"`
	Heartstatus     string `json:"heartstatus"`
	Heartname       string `json:"heartname"`
	Algorithmstatus string `json:"algorithmstatus"`
	Algorithmname   string `json:"algorithmname"`
	Spleenstatus    string `json:"spleenstatus"`
	Spleenname      string `json:"spleenname"`
	Lungstatus      string `json:"lungstatus"`
	Lungsname       string `json:"lungsname"`
	Renalstatus     string `json:"renalstatus"`
	Renalname       string `json:"renalname"`
	Addtime         int64  `json:"addtime"`
	Risknums        int    `json:"risknums"`
	Pdfurl          string `json:"pdfurl"`
	Lock            int    `json:"lock"`
}

// UserLiufu 六腑
type UserLiufu struct {
	Id            int    `json:"id"`
	Uid           int    `json:"uid"`
	Pid           int    `json:"pid"`
	Title         string `json:"title"`
	Gallstatus    string `json:"gallstatus"`
	Gallname      string `json:"gallname"`
	Stomachstatus string `json:"stomachstatus"`
	Stomachname   string `json:"stomachname"`
	Smallstatus   string `json:"smallstatus"`
	Smallname     string `json:"smallname"`
	Largestatus   string `json:"largestatus"`
	Largename     string `json:"largename"`
	Bladderstatus string `json:"bladderstatus"`
	Bladdername   string `json:"bladdername"`
	Addtime       int64  `json:"addtime"`
	Risknums      int    `json:"risknums"`
	Pdfurl        string `json:"pdfurl"`
	Lock          int    `json:"lock"`
}

// Tizhi 体质
type Tizhi struct {
	Id              int    `json:"id"`
	Uid             int    `json:"uid"`
	Pid             int    `json:"pid"`
	Title           string `json:"title"`
	Constitution    string `json:"constitution"`
	Constitutioname string `json:"constitutioname"`
	Addtime         int64  `json:"addtime"`
	Risknums        int    `json:"risknums"`
	Pdfurl          string `json:"pdfurl"`
	Lock            int    `json:"lock"`
}

// Userunscramble 症状程度表
type UserUnscramble struct {
	Id       int    `json:"id"`
	Name     string `json:"name"`
	Level    string `json:"level"`
	Typename string `json:"typename"`
	Content  string `json:"content"`
}

// 重疾病
type Dabing struct {
	Id       int    `json:"id"`
	Uid      int    `json:"uid"`
	Pid      int    `json:"pid"`
	Title    string `json:"title"`
	Apoplexy string `json:"apoplexy"`
	Heart    string `json:"heart"`
	Tumour   string ` json:"tumour"`
	Addtime  int64  `json:"addtime"`
	Risknums int    `json:"risknums"`
	Pdfurl   string `json:"pdfurl"`
	Lock     int    `json:"lock"`
}
type PulseInfo struct {
	Push         []Pulse       `json:"push"`
	Internal_5   []UserWuzhang `json:"internal"`
	Organs_6     []UserLiufu   `json:"organs"`
	Disease      []Dabing      `json:"disease"`
	Constitution []Tizhi       `json:"constitution"`
}

// 带推荐产品信息的诊断结构体
type PulseInfoA struct {
	Push         []Pulse       `json:"push"`
	Internal_5   []UserWuzhang `json:"internal"`
	Organs_6     []UserLiufu   `json:"organs"`
	Disease      []Dabing      `json:"disease"`
	Constitution []Tizhi       `json:"constitution"`
	Product      *Product      `json:"product"`
	//Product_l    []Product     `json:"product_l"`
}

// 诊断结果解读方案合集
type PulseInfoB struct {
	Push      *Pulse `json:"push"`
	Interpret string `json:"interpret"`
}

// 微信用户信息
type RespWXInfo struct {
	Openid     string `json:"openid"`      //用户唯一标识
	Sessionkey string `json:"session_key"` //会话**
	Unionid    string `json:"unionid"`     //用户在开放平台的唯一标识符，在满足 UnionID 下发条件的情况下会返回，详见 UnionID 机制说明。
	Errcode    int    `json:"errcode"`     //错误码
	ErrMsg     string `json:"errMsg"`      //错误信息
	Uid        int    `json:"uid"`
	Token      string `json:"token"` //jwt token
	Nickname   string `json:"nickname"`
	Headimgurl string `json:"headimgurl"`
}

func (f *Uuser) TableName() string {
	return "hr_wx_user"
}

// Find 验证用户是否存在
func (f *Uuser) Find(c *gin.Context, tx *gorm.DB, openid string, tj int, fid int) (token string, uid int) {
	fmt.Println(tj)
	fmt.Println(fid)
	user := &Uuser{}
	tx.Table("hr_wx_user").Where("openid = ?", openid).First(&user)
	fmt.Println("userinfo")
	fmt.Println(user)
	//判断是新会员
	if len(user.Openid) == 0 {

		if tj == 0 {
			tj = 1 //默认管理师
		}
		//赠送一个月
		now := time.Now().Unix() + 86400*30
		//用户ip
		reqIP := c.ClientIP()
		if reqIP == "::1" {
			reqIP = "127.0.0.1"
		}
		//请求微信用户信息
		//appId := viper.Get("wxConfig.appId")
		//appSecret := viper.Get("wxConfig.appsecret")
		//accessToken, _ := requestToken("wx2986f0dea031f5a8", "90f0829c1163d1cb249dd006f48d180a")
		//log.Println(accessToken)
		//reqUrl := "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s" // 拼接请求地址
		//response, err := http.Get(fmt.Sprintf(reqUrl, accessToken, openid))
		//if err != nil {
		//	middleware.ResponseError(c, 100, err)
		//	return
		//}
		//defer response.Body.Close()
		//infoBody, err := ioutil.ReadAll(response.Body)
		//if err != nil {
		//	middleware.ResponseError(c, 100, errors.New("resp error"))
		//	return
		//}
		//var objInfo RespWXInfo
		//log.Println("objInfo--------------")
		//log.Println(string(infoBody))
		//err = json.Unmarshal(infoBody, &objInfo)
		//if err != nil {
		//	return
		//}
		log.Println("1111111111111111111111111")
		useradd := Uuser2{Openid: openid, Huid: tj, Fromuid: fid, Endtime: now, Regip: reqIP, Times: 12} //Headimgurl: objInfo.Headimgurl,
		log.Println("useradd")
		log.Println(useradd)
		err := tx.Table("hr_wx_user").Create(&useradd).Error
		log.Println(err)
		toke, _ := jwt.GenerateToken(useradd.Id)

		token = toke
		uid = useradd.Id
	} else {
		//tx.Table("hr_wx_user").Where("id=?",user.Id).Update("token",token)
		toke, _ := jwt.GenerateToken(user.Id)

		token = toke
		uid = user.Id
	}
	return token, uid
}

func requestToken(appid, secret string) (string, error) {
	u, err := url.Parse("https://api.weixin.qq.com/cgi-bin/token")
	if err != nil {
		return "", err
	}
	paras := &url.Values{}
	//设置请求参数
	paras.Set("appid", appid)
	paras.Set("secret", secret)
	paras.Set("grant_type", "client_credential")
	u.RawQuery = paras.Encode()
	resp, err := http.Get(u.String())
	//关闭资源
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return "", errors.New("request token err :" + err.Error())
	}

	jMap := make(map[string]interface{})
	err = json.NewDecoder(resp.Body).Decode(&jMap)
	if err != nil {
		return "", errors.New("request token response json parse err :" + err.Error())
	}
	if jMap["errcode"] == nil || jMap["errcode"] == 0 {
		accessToken, _ := jMap["access_token"].(string)
		return accessToken, nil
	} else {
		//返回错误信息
		errcode := jMap["errcode"].(string)
		errmsg := jMap["errmsg"].(string)
		err = errors.New(errcode + ":" + errmsg)
		return "", err
	}
}

const MaxWidth float64 = 600

func fixSize(img1W, img2W int) (new1W, new2W int) {
	var ( //为了方便计算，将两个图片的宽转为 float64
		img1Width, img2Width = float64(img1W), float64(img2W)
		ratio1, ratio2       float64
	)

	minWidth := math.Min(img1Width, img2Width) // 取出两张图片中宽度最小的为基准

	if minWidth > 600 { // 如果最小宽度大于600，那么两张图片都需要进行缩放
		ratio1 = MaxWidth / img1Width // 图片1的缩放比例
		ratio2 = MaxWidth / img2Width // 图片2的缩放比例

		// 原宽度 * 比例 = 新宽度
		return int(img1Width * ratio1), int(img2Width * ratio2)
	}

	// 如果最小宽度小于600，那么需要将较大的图片缩放，使得两张图片的宽度一致
	if minWidth == img1Width {
		ratio2 = minWidth / img2Width // 图片2的缩放比例
		return img1W, int(img2Width * ratio2)
	}

	ratio1 = minWidth / img1Width // 图片1的缩放比例
	return int(img1Width * ratio1), img2W
}

// 会员生成推广码
func (f *Uuser) GetWXcode(c *gin.Context, tx *gorm.DB, uid int) (error, string) {

	//根据会员查询是否已有qr
	user := &Uuser{}
	err := tx.Table("hr_wx_user").Where("id = ?", uid).First(&user).Error
	if err != nil {
		return err, ""
	}
	if len(user.Qr) > 0 {
		return nil, user.Qr
	}
	accessToken, _ := requestToken("wx2986f0dea031f5a8", "90f0829c1163d1cb249dd006f48d180a")
	path := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken
	client := &http.Client{}
	params := `{"scene":"fid=` + jwt.String(int32(user.Id)) + `,hid=` + jwt.String(int32(user.Huid)) + `", "page": "pages/index/index"}`
	reqBody := bytes.NewBuffer([]byte(params))
	request, _ := http.NewRequest("POST", path, reqBody)
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	response, _ := client.Do(request)
	fmt.Println(response)
	if response.StatusCode == 200 {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return err, ""
		}
		bufstore := make([]byte, 5000000)         //数据缓存
		base64.StdEncoding.Encode(bufstore, body) // 文件转base64
		filename := jwt.Generate(time.Now()) + ".png"
		_ = ioutil.WriteFile(filename, body, 0666) //直接写入到文件就ok完活了。
		client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI5tGQntrEsXrVD4ZKH6rF", "kwnU0K1xyp0YZism6eilflHIxLadb7")
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		bucket, err := client.Bucket("jiankangdanganguan2")

		if err != nil {
			// HandleError(err)
			return err, ""
		}

		err = bucket.PutObjectFromFile("userqrcode/"+filename, "./"+filename)
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		//删除本地生成的Pdf
		err = os.Remove(filename)
		if err != nil {
			return err, ""
		} else {
			// 删除成功
			filepath := "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/userqrcode/" + filename
			//(&UserLiufu{}).LfPdfSave(c, tx, id, filepath)
			u := Uuser{Qr: filepath}
			tx.Table("hr_wx_user").Where("id = ?", uid).Update(&u)
			return nil, filepath
		}
	}
	//return nil
	return nil, ""

}

// 代理生成推广码
func (f *Uuser) Scheme(c *gin.Context, tx *gorm.DB, fid string) (error, string) {
	user := &Admin{}
	err := tx.Table("hr_admin_user").Where("id = ?", fid).First(&user).Error
	if err != nil {
		return err, ""
	}
	//if len(user.Url)>0{
	//	return nil,user.Url
	//}
	accessToken, _ := requestToken("wx2986f0dea031f5a8", "90f0829c1163d1cb249dd006f48d180a")
	url := "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + accessToken
	client := &http.Client{}
	//params := "{'jump_wxa':{'path':'pages/index/index','query':'fid=0&hid=3'},'is_expire':true,'expire_time':'1656326128'}"
	params := `{"jump_wxa":{"path": "/pages/index/index","query":"fid=0&hid=3"},"expire_time":1703673328}`
	reqBody := bytes.NewBuffer([]byte(params))
	request, _ := http.NewRequest("POST", url, reqBody)
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	response, _ := client.Do(request)
	if response.StatusCode == 200 {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return err, ""
		}
		log.Println(string(body))

		//bufstore := make([]byte, 5000000)                     //数据缓存
		//base64.StdEncoding.Encode(bufstore, body)               // 文件转base64
		//filename:=jwt.Generate(time.Now()) + ".png"
		//_ = ioutil.WriteFile(filename, body, 0666) //直接写入到文件就ok完活了。
		//client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI5tGQntrEsXrVD4ZKH6rF", "kwnU0K1xyp0YZism6eilflHIxLadb7")
		//if err != nil {
		//	// HandleError(err)
		//	return err,""
		//}
		//bucket, err := client.Bucket("jiankangdanganguan2")
		//
		//if err != nil {
		//	// HandleError(err)
		//	return err,""
		//}
		//
		//err = bucket.PutObjectFromFile("userqrcode/"+filename, "./"+filename)
		//if err != nil {
		//	// HandleError(err)
		//	return err,""
		//}
		////删除本地生成的Pdf
		//err = os.Remove(filename)
		//if err != nil {
		//	return err,""
		//} else {
		//	// 删除成功
		//	filepath := "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/userqrcode/" + filename
		//	//(&UserLiufu{}).LfPdfSave(c, tx, id, filepath)
		//	u:=Admin{Url:filepath }
		//	tx.Table("hr_admin_user").Where("id = ?", fid).Update(&u)
		//	return nil,filepath
		//}
	}
	//return nil
	return nil, ""

}

// 代理生成推广码//
func (f *Uuser) DlWXcode2(c *gin.Context, tx *gorm.DB, uid int) (error, string) {
	//根据会员查询是否已有qr
	user := &Uuser{}
	err := tx.Table("hr_wx_user").Where("id = ?", uid).First(&user).Error
	if err != nil {
		return err, ""
	}
	//if len(user.Qr) > 0 {
	//	return nil, user.Qr
	//}
	accessToken, _ := requestToken("wx2986f0dea031f5a8", "90f0829c1163d1cb249dd006f48d180a")
	path := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken
	client := &http.Client{}
	params := `{"scene":"fid=` + jwt.String(int32(user.Id)) + `,t_code=133256,hid=0", "page": "pages/index/index"}`
	reqBody := bytes.NewBuffer([]byte(params))
	request, _ := http.NewRequest("POST", path, reqBody)
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	response, _ := client.Do(request)
	fmt.Println(response)
	if response.StatusCode == 200 {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return err, ""
		}
		bufstore := make([]byte, 5000000)         //数据缓存
		base64.StdEncoding.Encode(bufstore, body) // 文件转base64
		filename := jwt.Generate(time.Now()) + ".png"
		_ = ioutil.WriteFile(filename, body, 0666) //直接写入到文件就ok完活了。
		client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI5tGQntrEsXrVD4ZKH6rF", "kwnU0K1xyp0YZism6eilflHIxLadb7")
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		bucket, err := client.Bucket("jiankangdanganguan2")

		if err != nil {
			// HandleError(err)
			return err, ""
		}

		err = bucket.PutObjectFromFile("userqrcode/"+filename, "./"+filename)
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		//删除本地生成的Pdf
		err = os.Remove(filename)
		if err != nil {
			return err, ""
		} else {
			// 删除成功
			filepath := "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/userqrcode/" + filename
			//(&UserLiufu{}).LfPdfSave(c, tx, id, filepath)
			u := Uuser{Qr: filepath}
			tx.Table("hr_wx_user").Where("id = ?", uid).Update(&u)
			return nil, filepath
		}
	}
	//return nil
	return nil, ""
}

// 代理生成推广码
func (f *Uuser) DlWXcode(c *gin.Context, tx *gorm.DB, fid string) (error, string) {
	user := &Admin{}
	err := tx.Table("hr_admin_user").Where("id = ?", fid).First(&user).Error
	if err != nil {
		return err, ""
	}
	if len(user.Url) > 0 {
		return nil, user.Url
	}
	accessToken, _ := requestToken("wx2986f0dea031f5a8", "90f0829c1163d1cb249dd006f48d180a")
	path := "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken
	client := &http.Client{}
	params := `{"scene":"fid=0,hid=` + fid + `", "page": "pages/index/index"}`
	reqBody := bytes.NewBuffer([]byte(params))
	request, _ := http.NewRequest("POST", path, reqBody)
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	response, _ := client.Do(request)
	fmt.Println(response)
	if response.StatusCode == 200 {
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return err, ""
		}
		bufstore := make([]byte, 5000000)         //数据缓存
		base64.StdEncoding.Encode(bufstore, body) // 文件转base64
		filename := jwt.Generate(time.Now()) + ".png"
		_ = ioutil.WriteFile(filename, body, 0666) //直接写入到文件就ok完活了。
		client, err := oss.New("oss-cn-beijing.aliyuncs.com", "LTAI5tGQntrEsXrVD4ZKH6rF", "kwnU0K1xyp0YZism6eilflHIxLadb7")
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		bucket, err := client.Bucket("jiankangdanganguan2")

		if err != nil {
			// HandleError(err)
			return err, ""
		}

		err = bucket.PutObjectFromFile("userqrcode/"+filename, "./"+filename)
		if err != nil {
			// HandleError(err)
			return err, ""
		}
		//删除本地生成的Pdf
		err = os.Remove(filename)
		if err != nil {
			return err, ""
		} else {
			// 删除成功
			filepath := "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/userqrcode/" + filename
			//(&UserLiufu{}).LfPdfSave(c, tx, id, filepath)
			u := Admin{Url: filepath}
			tx.Table("hr_admin_user").Where("id = ?", fid).Update(&u)
			return nil, filepath
		}
	}
	//return nil
	return nil, ""

}

// FindUser 查询用户信息
func (f *Uuser) FindUser(c *gin.Context, tx *gorm.DB, uid int) (error, *Uuser) {

	user := &Uuser{} //
	err := tx.Table("hr_wx_user").Where("id = ?", uid).First(&user).Error
	if err != nil {
		return err, nil
	}
	var res []UserExtract
	errU := tx.Table("hr_user_extract").Where("uid=? and status=0", uid).Find(&res).Error
	if errU != nil {
		return errU, nil
	}
	//遍历res，加总extract_price求和
	var sum float64
	for _, v := range res {
		sum += v.ExtractPrice
	}
	//sum转float
	dSum := decimal.NewFromFloat(sum)
	//判断如果dSum小于0
	if dSum.LessThan(decimal.NewFromFloat(0)) {
		dSum = decimal.NewFromFloat(0)
	}
	// 执行算术运算
	result := user.Money.Sub(dSum)
	user.Money = result
	//是否线上专家讲堂
	user.Show = 0
	return nil, user
}

// AdminUser 健康管理师 修改直接上级带级别的会员
func (f *Admin) AdminUser(c *gin.Context, tx *gorm.DB, uid int) (*Admin, error) {
	user := &Uuser{}
	err := tx.Table("hr_wx_user").Where("id = ?", uid).First(&user).Error
	if err != nil {
		return nil, err
	}
	suid := GEtLevel(c, tx, user.Fromuid)
	log.Println("Fromuid--------")
	log.Println(user.Fromuid)
	var u2 Uuser
	tx.Table("hr_wx_user").Where("id = ?", user.Fromuid).First(&u2) //suid
	//获取带升级
	admin := Admin{
		Id:         suid,
		Truename:   u2.Truename,
		Username:   u2.Truename,
		Phone:      u2.Userphone,
		Headimgurl: "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/jiankang/guanlishi.png",
		Cons:       5,
		Praise:     5,
		Context:    "健康管理师",
		Star:       string(5),
		Area:       "山东威海",
		Url:        "https://jiankangdanganguan2.oss-cn-beijing.aliyuncs.com/jiankang/guanlishi.png",
	}
	if err != nil {
		return nil, err
	}
	return &admin, nil
}

// UserPulse 数字脉诊数据存储
func (f *Pulse) UserPulse(c *gin.Context, tx *gorm.DB, uid, leftrate, leftlowpre, lefthightpre, rightrate, rightlowpre, righthightpre int) (error, int) {
	pushAdd := Pulse{Uid: uid, Leftrate: leftrate, Leftlowpre: leftlowpre, Lefthightpre: lefthightpre, Rightrate: rightrate, Rightlowpre: rightlowpre, Righthightpre: righthightpre, Addtime: time.Now().Unix(), Status: 0, Del: 1}
	err := tx.Table("hr_wx_pulse").Create(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, pushAdd.Id
}

// UserPulse 数字脉诊数据存储
func (f *UserWuzhang) WzPdfSave(c *gin.Context, tx *gorm.DB, id int, pdf string) (error, int) {
	pushAdd := UserWuzhang{Pdfurl: pdf, Lock: 1}
	err := tx.Table("hr_wx_wuzhang").Where("pid=?", id).Update(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, pushAdd.Id
}

// UserPulse 六腑
func (f *UserLiufu) LfPdfSave(c *gin.Context, tx *gorm.DB, id int, pdf string) (error, int) {
	pushAdd := UserLiufu{Pdfurl: pdf, Lock: 1}
	err := tx.Table("hr_wx_liufu").Where("pid=?", id).Update(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, pushAdd.Id
}

// UserPulse 体质
func (f *Tizhi) TzPdfSave(c *gin.Context, tx *gorm.DB, id int, pdf string) (error, int) {
	pushAdd := Tizhi{Pdfurl: pdf, Lock: 1}
	err := tx.Table("hr_wx_tizhi").Where("pid=?", id).Update(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, pushAdd.Id
}

// UserPulse 体质
func (f *Dabing) DbPdfSave(c *gin.Context, tx *gorm.DB, id int, pdf string) (error, int) {
	pushAdd := Dabing{Pdfurl: pdf, Lock: 1}
	err := tx.Table("hr_wx_dabing").Where("pid=?", id).Update(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, pushAdd.Id
}

// UserSelect  数字脉诊数据查询  多条
func (f *Pulse) UserSelect(c *gin.Context, tx *gorm.DB, uid int) (error, []Pulse) {
	var res []Pulse
	err := tx.Table("hr_wx_pulse").Where("uid=? and status=1", uid).Order("id desc").Find(&res).Error
	fmt.Println(res)
	if err != nil {
		return err, nil
	}
	return nil, res
}

// UserPaulseOne  数字脉诊数据查询最新  单条
func (f *Pulse) UserPaulseOne(c *gin.Context, tx *gorm.DB, uid int) (error, *Pulse) {
	pulse := &Pulse{}
	err := tx.Table("hr_wx_pulse").Where("uid=? and status=1", uid).Order("id asc").Find(&pulse).Error
	//fmt.Println(pulse)
	if err != nil {
		//return err, nil
	}
	return nil, pulse
}

// UserSelect  数字脉诊数据查询 单挑
func (f *Pulse) UserFind(c *gin.Context, tx *gorm.DB, id int) (error, []Pulse) {
	var res []Pulse

	err := tx.Table("hr_wx_pulse").Where("id=?", id).Find(&res).Error
	if err != nil {
		return err, nil
	}
	return nil, res
}

// UserSelect  数字脉诊数据查询 单挑
func (f *Pulse) UserFindLast(c *gin.Context, tx *gorm.DB, uid int) (error, []Pulse) {
	var res []Pulse
	err := tx.Table("hr_wx_pulse").Where("uid=?", uid).Last(&res).Error
	if err != nil {
		return err, nil
	}

	return nil, res
}

// UserUpdate  数字脉诊数据存储  更新为有效
func (f *Pulse) UserUpdate(c *gin.Context, tx *gorm.DB, id int) (error, int) {
	pushAdd := Pulse{Status: 1}
	err := tx.Table("hr_wx_pulse").Where("id=? ", id).Updates(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, id
}

type DbList struct {
	Name  string `json:"name"`
	Level string `json:"level"`
}

// 检查4项结果
func (f *PulseInfo) PulseInfo(c *gin.Context, tx *gorm.DB, id int) (error, *PulseInfo) {
	//
	err, pulsh := (&Pulse{}).UserFind(c, tx, id)
	if err != nil {
		return err, nil
	}

	err, wz := (&UserWuzhang{}).Wuzhang(c, tx, id)

	if err != nil {
		return err, nil
	}
	err, liuf := (&UserLiufu{}).Liufu(c, tx, id)
	if err != nil {
		return err, nil
	}
	err, dabing := (&Dabing{}).DabingFind(c, tx, id)
	if err != nil {
		return err, nil
	}
	err, tizhi := (&Tizhi{}).TizhiFind(c, tx, id)
	if err != nil {
		return err, nil
	}
	pulse := &PulseInfo{
		pulsh,
		wz,
		liuf,
		dabing,
		tizhi,
	}
	fmt.Println(pulse)
	return nil, pulse
}

// 检查4项结果，匹配产品
func (f *PulseInfoA) PulseInfoA(c *gin.Context, tx *gorm.DB, id int) (error, *PulseInfoA) {
	//
	err, pulsh := (&Pulse{}).UserFind(c, tx, id)
	if err != nil {
		return err, nil
	}
	var DbLists []DbList

	var Db DbList
	err, wz := (&UserWuzhang{}).Wuzhang(c, tx, id)

	Db.Level = wz[0].Heartstatus
	Db.Name = wz[0].Heartname
	DbLists = append(DbLists, Db)
	Db.Level = wz[0].Algorithmstatus
	Db.Name = wz[0].Algorithmname
	DbLists = append(DbLists, Db)
	Db.Level = wz[0].Spleenstatus
	Db.Name = wz[0].Spleenname
	DbLists = append(DbLists, Db)
	Db.Level = wz[0].Lungstatus
	Db.Name = wz[0].Lungsname
	DbLists = append(DbLists, Db)
	Db.Level = wz[0].Renalstatus
	Db.Name = wz[0].Renalname
	DbLists = append(DbLists, Db)
	bingList := []string{"严重", "重度", "中度"}
	level := ""
	name := ""
	for _, vv := range bingList {
		if len(name) > 0 {
			break
		}
		for _, v := range DbLists {
			if vv == v.Level {
				level = v.Level
				name = v.Name
				break
			}
		}
	}
	//程度查询
	log.Println(level)
	_, ress := (&UserUnscramble{}).ChengduFind(c, tx, name, level)

	//log.Println("11111111111111")
	//log.Println(ress.Id)
	products := &Product{}
	if ress != nil {
		_, products = (&Product{}).FindProductByC(c, tx, ress.Id)
	}

	//log.Println("22222222222222")
	//log.Println(products)
	if err != nil {
		return err, nil
	}
	err, liuf := (&UserLiufu{}).Liufu(c, tx, id)
	log.Println("33333333333333333")
	log.Println(liuf)
	if err != nil {
		return err, nil
	}

	err, dabing := (&Dabing{}).DabingFind(c, tx, id)
	log.Println("6666666666666")
	log.Println(dabing)
	if err != nil {
		return err, nil
	}
	err, tizhi := (&Tizhi{}).TizhiFind(c, tx, id)
	if err != nil {
		return err, nil
	}
	pulse := &PulseInfoA{
		pulsh,
		wz,
		liuf,
		dabing,
		tizhi,
		products,
	}
	return nil, pulse
}

// 检查4项结果，匹配产品
func (f *PulseInfoB) PulseInfoB(c *gin.Context, tx *gorm.DB) (error, *PulseInfoB) {
	var interpret string
	token := c.Request.Header.Get("token") //从headers获取token
	claims, err := jwt.ParseToken(token)
	err, pulsh := (&Pulse{}).UserPaulseOne(c, tx, claims.Uid)
	if err != nil {
		//return err, nil
	}
	//var DbLists []DbList
	if pulsh.Id > 0 {
		var Db DbList
		err, wz := (&UserWuzhang{}).Wuzhang(c, tx, pulsh.Id)
		//1
		Db.Level = wz[0].Heartstatus
		Db.Name = wz[0].Heartname
		//心脏程度查询
		_, res1 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if res1 != nil {
			interpret1 := res1.Content
			if interpret1 != "" {
				interpret = interpret + res1.Content
				//log.Println(interpret1)
			}
		}
		//DbLists = append(DbLists, Db)
		//2
		Db.Level = wz[0].Algorithmstatus
		Db.Name = wz[0].Algorithmname
		//肝脏程度查询
		_, res2 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if res2 != nil {
			interpret2 := res2.Content
			if interpret2 != "" {
				interpret = interpret + res2.Content
				//log.Println(interpret2)
			}
		}
		//DbLists = append(DbLists, Db)
		//3
		Db.Level = wz[0].Spleenstatus
		Db.Name = wz[0].Spleenname
		//脾程度查询
		_, res3 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if res3 != nil {
			interpret3 := res3.Content
			if interpret3 != "" {
				interpret = interpret + res3.Content
				//log.Println(interpret3)
			}
		}
		//DbLists = append(DbLists, Db)
		//4
		Db.Level = wz[0].Lungstatus
		Db.Name = wz[0].Lungsname
		//肺程度查询
		_, res4 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if res4 != nil {
			interpret4 := res4.Content
			if interpret4 != "" {
				interpret = interpret + res4.Content
				//log.Println(interpret4)
			}
		}
		//DbLists = append(DbLists, Db)
		//5
		Db.Level = wz[0].Renalstatus
		Db.Name = wz[0].Renalname
		//肾程度查询
		_, res5 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if res5 != nil {
			interpret5 := res4.Content
			if interpret5 != "" {
				interpret = interpret + res5.Content
				//log.Println(interpret5)
			}
		}
		//DbLists = append(DbLists, Db)

		err, liuf := (&UserLiufu{}).Liufu(c, tx, pulsh.Id)
		log.Println("六腑")
		log.Println(liuf)
		if err != nil {
			return err, nil
		}
		//1
		Db.Level = liuf[0].Gallstatus
		Db.Name = liuf[0].Gallname
		//胆程度查询
		_, resL1 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resL1 != nil {
			interpretL1 := resL1.Content
			if interpretL1 != "" {
				interpret = interpret + resL1.Content
				//log.Println(interpret1)
			}
		}
		//DbLists = append(DbLists, Db)
		//2
		Db.Level = liuf[0].Stomachstatus
		Db.Name = liuf[0].Stomachname
		//胃程度查询
		_, resL2 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resL2 != nil {
			interpretL2 := resL2.Content
			if interpretL2 != "" {
				interpret = interpret + resL2.Content
				//log.Println(interpret2)
			}
		}
		//DbLists = append(DbLists, Db)
		//3
		Db.Level = liuf[0].Smallstatus
		Db.Name = liuf[0].Smallname
		//小肠程度查询
		_, resL3 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resL3 != nil {
			interpretL3 := resL3.Content
			if interpretL3 != "" {
				interpret = interpret + resL3.Content
				//log.Println(interpret3)
			}
		}
		//DbLists = append(DbLists, Db)
		//4
		Db.Level = liuf[0].Largestatus
		Db.Name = liuf[0].Largename
		//大肠程度查询
		_, resL4 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resL4 != nil {
			interpretL4 := resL4.Content
			if interpretL4 != "" {
				interpret = interpret + resL4.Content
				//log.Println(interpret4)
			}
		}
		//DbLists = append(DbLists, Db)
		//5
		Db.Level = liuf[0].Bladderstatus
		Db.Name = liuf[0].Bladdername
		//膀胱程度查询
		_, resL5 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resL5 != nil {
			interpretL5 := resL5.Content
			if interpretL5 != "" {
				interpret = interpret + resL5.Content
				//log.Println(interpret5)
			}
		}
		//DbLists = append(DbLists, Db)
		//大病
		err, dabing := (&Dabing{}).DabingFind(c, tx, pulsh.Id)
		log.Println("大病")
		log.Println(dabing)
		if err != nil {
			return err, nil
		}
		//1
		Db.Level = dabing[0].Apoplexy
		Db.Name = "中风预警"
		//中风程度查询
		_, resD1 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resD1 != nil {
			interpretD1 := resD1.Content
			if interpretD1 != "" {
				interpret = interpret + resD1.Content
				//log.Println(interpret1)
			}
		}
		//DbLists = append(DbLists, Db)
		//2
		Db.Level = dabing[0].Heart
		Db.Name = "心脏病预警"
		//心脏病程度查询
		_, resD2 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resD2 != nil {
			interpretD2 := resD2.Content
			if interpretD2 != "" {
				interpret = interpret + resD2.Content
				//log.Println(interpret2)
			}
		}
		//DbLists = append(DbLists, Db)
		//3
		Db.Level = dabing[0].Tumour
		Db.Name = "肿瘤预警"
		//肿瘤预警程度查询
		_, resD3 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resD3 != nil {
			interpretD3 := resD3.Content
			if interpretD3 != "" {
				interpret = interpret + resD3.Content
				//log.Println(interpret3)
			}
		}
		//DbLists = append(DbLists, Db)
		err, tizhi := (&Tizhi{}).TizhiFind(c, tx, pulsh.Id)
		log.Println("体质")
		log.Println(dabing)
		if err != nil {
			return err, nil
		}
		//1
		Db.Level = tizhi[0].Constitution
		Db.Name = tizhi[0].Constitutioname
		//体质程度查询
		_, resT1 := (&UserUnscramble{}).ChengduFind(c, tx, Db.Name, Db.Level)
		if resT1 != nil {
			interpretT1 := resT1.Content
			if interpretT1 != "" {
				interpret = interpret + resT1.Content
				//log.Println(interpret1)
			}
		}
		//DbLists = append(DbLists, Db)

		interpret = html.UnescapeString(interpret)

		pulse := &PulseInfoB{
			pulsh,
			interpret,
		}
		return nil, pulse
	} else {
		pulse := &PulseInfoB{}
		return nil, pulse
	}

}

// 检查4项 最近一次
func (f *PulseInfo) PulseInfoLast(c *gin.Context, tx *gorm.DB, uid int) (error, *PulseInfo) {

	err, pulsh := (&Pulse{}).UserFindLast(c, tx, uid)
	if err != nil {
		return err, nil
	}
	//if len(pulsh) <= 0 {
	//	return errors.New("未查到记录"), nil
	//}
	if len(pulsh) > 0 {
		err, wz := (&UserWuzhang{}).Wuzhang(c, tx, pulsh[0].Id)
		if err != nil {
			return err, nil
		}
		err, liuf := (&UserLiufu{}).Liufu(c, tx, pulsh[0].Id)
		if err != nil {
			return err, nil
		}
		err, dabing := (&Dabing{}).DabingFind(c, tx, pulsh[0].Id)
		if err != nil {
			return err, nil
		}
		err, tizhi := (&Tizhi{}).TizhiFind(c, tx, pulsh[0].Id)
		if err != nil {
			return err, nil
		}
		pulse := &PulseInfo{
			pulsh,
			wz,
			liuf,
			dabing,
			tizhi,
		}
		return nil, pulse
	} else {
		//定义一个空的PulseInfo结构体，赋值给pulse
		pulse := &PulseInfo{}
		return nil, pulse
	}

}

// 五脏查询
func (f *UserWuzhang) Wuzhang(c *gin.Context, tx *gorm.DB, id int) (error, []UserWuzhang) {
	var wz []UserWuzhang
	err := tx.Table("hr_wx_wuzhang").Where("pid=?", id).Find(&wz).Error
	if err != nil {
		return err, nil
	}
	return nil, wz
}

// 大病查询
func (f *Dabing) DabingFind(c *gin.Context, tx *gorm.DB, id int) (error, []Dabing) {
	var wz []Dabing
	err := tx.Table("hr_wx_dabing").Where("pid=?", id).Find(&wz).Error
	if err != nil {
		return err, nil
	}
	return nil, wz
}

// 六腑查询
func (f *UserLiufu) Liufu(c *gin.Context, tx *gorm.DB, id int) (error, []UserLiufu) {
	var wz []UserLiufu
	err := tx.Table("hr_wx_liufu").Where("pid=?", id).Find(&wz).Error
	if err != nil {
		return err, nil
	}
	return nil, wz
}

// 体质查询
func (f *Tizhi) TizhiFind(c *gin.Context, tx *gorm.DB, id int) (error, []Tizhi) {
	var wz []Tizhi
	err := tx.Table("hr_wx_tizhi").Where("pid=?", id).Find(&wz).Error
	if err != nil {
		return err, nil
	}
	return nil, wz
}

// 程度查询
func (f *UserUnscramble) ChengduFind(c *gin.Context, tx *gorm.DB, name string, level string) (error, *UserUnscramble) {
	wz := &UserUnscramble{}
	err := tx.Table("hr_wx_user_unscramble").Where("name=? and level=?", name, level).Find(&wz).Error
	if err != nil {
		return err, nil
	}
	return nil, wz
}

// UserUpdate  数字脉诊数据存储  更新为有效
func (f *Pulse) UserUpdate2(c *gin.Context, tx *gorm.DB, id int) (error, int) {
	pushAdd := Pulse{Del: 100}
	fmt.Println(pushAdd)
	fmt.Println(id)
	err := tx.Table("hr_wx_pulse").Where("id=?", id).Updates(&pushAdd).Error
	if err != nil {
		return err, 0
	}
	return nil, id
}

// UserWuzhang 数字脉诊数据生成 五脏
func (f *UserWuzhang) UserWuzhang(c *gin.Context, tx *gorm.DB, pid, uid, leftrate, leftlowpre, lefthightpre, rightrate, rightlowpre, righthightpre int) (error, int) {
	//心脏功能 左侧低压
	heartstatus := "正常"
	heartname := "心脏功能正常"
	risknums := 0
	if leftlowpre <= 54 {
		heartstatus = "严重"
		heartname = "心血虚"
		risknums = risknums + 1
	} else if leftlowpre >= 55 && leftlowpre <= 59 {
		heartstatus = "重度"
		heartname = "心血虚"
	} else if leftlowpre >= 60 && leftlowpre <= 64 {
		heartstatus = "中度"
		heartname = "心血虚"
	} else if leftlowpre >= 65 && leftlowpre <= 69 {
		heartstatus = "轻度"
		heartname = "心血虚"
	} else if leftlowpre >= 70 && leftlowpre <= 80 {
		heartstatus = "正常"
		heartname = "心脏功能正常"
	} else if leftlowpre >= 81 && leftlowpre <= 85 {
		heartstatus = "轻度"
		heartname = "心阴虚"
	} else if leftlowpre >= 86 && leftlowpre <= 90 {
		heartstatus = "中度"
		heartname = "心阴虚"
	} else if leftlowpre >= 91 && leftlowpre <= 95 {
		heartstatus = "重度"
		heartname = "心阴虚"
	} else if leftlowpre >= 96 {
		heartstatus = "严重"
		heartname = "心阴虚"
		risknums = risknums + 1
	}
	//肝脏 左侧高压
	algorithmstatus := "正常"
	algorithmname := "肝脏功能正常"
	if lefthightpre <= 79 {
		algorithmstatus = "严重"
		algorithmname = "肝血虚"
		risknums = risknums + 1
	} else if lefthightpre >= 80 && lefthightpre <= 84 {
		algorithmstatus = "重度"
		algorithmname = "肝血虚"
	} else if lefthightpre >= 85 && lefthightpre <= 89 {
		algorithmstatus = "中度"
		algorithmname = "肝血虚"
	} else if lefthightpre >= 90 && lefthightpre <= 94 {
		algorithmstatus = "轻度"
		algorithmname = "肝血虚"
	} else if lefthightpre >= 95 && lefthightpre <= 110 {
		algorithmstatus = "正常"
		algorithmname = "肝脏功能正常"
	} else if lefthightpre >= 111 && lefthightpre <= 120 {
		algorithmstatus = "轻度"
		algorithmname = "肝气郁结"
	} else if lefthightpre >= 121 && lefthightpre <= 130 {
		algorithmstatus = "中度"
		algorithmname = "肝气郁结"
	} else if lefthightpre >= 131 && lefthightpre <= 140 {
		algorithmstatus = "重度"
		algorithmname = "肝气郁结"
	} else if lefthightpre >= 141 {
		algorithmstatus = "严重"
		algorithmname = "肝气郁结"
		risknums = risknums + 1
	}

	//脾脏 右侧低压
	spleenstatus := "正常"
	spleenname := "脾脏功能正常"
	if rightlowpre <= 54 {
		spleenstatus = "严重"
		spleenname = "脾阳虚"
		risknums = risknums + 1
	} else if rightlowpre >= 55 && rightlowpre <= 59 {
		spleenstatus = "重度"
		spleenname = "脾阳虚"
	} else if rightlowpre >= 60 && rightlowpre <= 64 {
		spleenstatus = "中度"
		spleenname = "脾阳虚"
	} else if rightlowpre >= 65 && rightlowpre <= 69 {
		spleenstatus = "轻度"
		spleenname = "脾阳虚"
	} else if rightlowpre >= 70 && rightlowpre <= 80 {
		spleenstatus = "正常"
		spleenname = "脾脏功能正常"
	} else if rightlowpre >= 81 && rightlowpre <= 85 {
		spleenstatus = "轻度"
		spleenname = "脾阴虚"
	} else if rightlowpre >= 86 && rightlowpre <= 90 {
		spleenstatus = "中度"
		spleenname = "脾阴虚"
	} else if rightlowpre >= 91 && rightlowpre <= 95 {
		spleenstatus = "重度"
		spleenname = "脾阴虚"
	} else if rightlowpre >= 96 {
		spleenstatus = "严重"
		spleenname = "脾阴虚"
		risknums = risknums + 1
	}

	//肺脏 右侧低压
	lungstatus := "正常"
	lungsname := "肺脏功能正常"
	if rightrate <= 54 {
		lungstatus = "严重"
		lungsname = "肺气虚"
		risknums = risknums + 1
	} else if rightrate >= 55 && rightrate <= 59 {
		lungstatus = "重度"
		lungsname = "肺气虚"
	} else if rightrate >= 60 && rightrate <= 64 {
		lungstatus = "中度"
		lungsname = "肺气虚"
	} else if rightrate >= 65 && rightrate <= 69 {
		lungstatus = "轻度"
		lungsname = "肺气虚"
	} else if rightrate >= 70 && rightrate <= 80 {
		lungstatus = "正常"
		lungsname = "肺脏功能正常"
	} else if rightrate >= 81 && rightrate <= 85 {
		lungstatus = "轻度"
		lungsname = "肺阴虚"
	} else if rightrate >= 86 && rightrate <= 90 {
		lungstatus = "中度"
		lungsname = "肺阴虚"
	} else if rightrate >= 91 && rightrate <= 95 {
		lungstatus = "重度"
		lungsname = "肺阴虚"
	} else if rightrate >= 96 {
		lungstatus = "严重"
		lungsname = "肺阴虚"
		risknums = risknums + 1
	}

	//肾脏功能 右侧脉搏
	renalstatus := "正常"
	renalname := "肾脏功能正常"
	if leftlowpre <= 54 {
		renalstatus = "严重"
		renalname = "肾阳虚"
		risknums = risknums + 1
	} else if leftlowpre >= 55 && leftlowpre <= 59 {
		renalstatus = "重度"
		renalname = "肾阳虚"
	} else if leftlowpre >= 60 && leftlowpre <= 64 {
		renalstatus = "中度"
		renalname = "肾阳虚"
	} else if leftlowpre >= 65 && leftlowpre <= 69 {
		renalstatus = "轻度"
		renalname = "肾阳虚"
	} else if leftlowpre >= 70 && leftlowpre <= 80 {
		renalstatus = "正常"
		renalname = "肾脏功能正常"
	} else if leftlowpre >= 81 && leftlowpre <= 85 {
		renalstatus = "轻度"
		renalname = "肾阴虚"
	} else if leftlowpre >= 86 && leftlowpre <= 90 {
		renalstatus = "中度"
		renalname = "肾阴虚"
	} else if leftlowpre >= 91 && leftlowpre <= 95 {
		renalstatus = "重度"
		renalname = "肾阴虚"
	} else if leftlowpre >= 96 {
		renalstatus = "严重"
		renalname = "肾阴虚"
		risknums = risknums + 1
	}

	wuZang := UserWuzhang{Uid: uid, Pid: pid, Title: "五脏", Heartstatus: heartstatus, Heartname: heartname, Algorithmstatus: algorithmstatus, Algorithmname: algorithmname, Spleenstatus: spleenstatus,
		Spleenname: spleenname, Lungstatus: lungstatus, Lungsname: lungsname, Renalstatus: renalstatus, Renalname: renalname, Addtime: time.Now().Unix(), Risknums: risknums}

	err := tx.Table("hr_wx_wuzhang").Create(&wuZang).Error
	if err != nil {
		return err, 0
	}
	return nil, wuZang.Id
}

// UserLiufu  数字脉诊数据生成 六腑
func (f *UserLiufu) UserLiufu(c *gin.Context, tx *gorm.DB, pid, uid, leftrate, leftlowpre, lefthightpre, rightrate, rightlowpre, righthightpre int) (error, int) {
	//胆功能正常 右侧高压
	gallstatus := "正常"
	gallname := "胆功能正常"
	risknums := 0
	if righthightpre <= 79 {
		gallstatus = "严重"
		gallname = "胆气虚"
		risknums = risknums + 1
	} else if righthightpre >= 80 && righthightpre <= 84 {
		gallstatus = "重度"
		gallname = "胆气虚"
	} else if righthightpre >= 85 && righthightpre <= 89 {
		gallstatus = "中度"
		gallname = "胆气虚"
	} else if righthightpre >= 90 && righthightpre <= 94 {
		gallstatus = "轻度"
		gallname = "胆气虚"
	} else if righthightpre >= 95 && righthightpre <= 110 {
		gallstatus = "正常"
		gallname = "胆功能正常"
	} else if righthightpre >= 111 && righthightpre <= 120 {
		gallstatus = "轻度"
		gallname = "胆气郁滞"
	} else if righthightpre >= 121 && righthightpre <= 130 {
		gallstatus = "中度"
		gallname = "胆气郁滞"
	} else if righthightpre >= 131 && righthightpre <= 140 {
		gallstatus = "重度"
		gallname = "胆气郁滞"
	} else if righthightpre >= 141 {
		gallstatus = "严重"
		gallname = "胆气郁滞"
		risknums = risknums + 1
	}
	//胃 右侧低压
	stomachstatus := "正常"
	stomachname := "胃功能正常"
	if rightlowpre <= 54 {
		stomachstatus = "严重"
		stomachname = "胃寒"
		risknums = risknums + 1
	} else if rightlowpre >= 55 && rightlowpre <= 59 {
		stomachstatus = "重度"
		stomachname = "胃寒"
	} else if rightlowpre >= 60 && rightlowpre <= 64 {
		stomachstatus = "中度"
		stomachname = "胃寒"
	} else if rightlowpre >= 65 && rightlowpre <= 69 {
		stomachstatus = "轻度"
		stomachname = "胃寒"
	} else if rightlowpre >= 70 && rightlowpre <= 80 {
		stomachstatus = "正常"
		stomachname = "胃功能正常"
	} else if rightlowpre >= 81 && rightlowpre <= 85 {
		stomachstatus = "轻度"
		stomachname = "胃热"
	} else if rightlowpre >= 86 && rightlowpre <= 90 {
		stomachstatus = "中度"
		stomachname = "胃热"
	} else if rightlowpre >= 91 && rightlowpre <= 95 {
		stomachstatus = "重度"
		stomachname = "胃热"
	} else if rightlowpre >= 96 {
		stomachstatus = "严重"
		stomachname = "胃热"
		risknums = risknums + 1
	}

	//小肠 右侧低压
	smallstatus := "正常"
	smallname := "小肠功能正常"
	if leftrate <= 54 {
		smallstatus = "严重"
		smallname = "小肠虚寒"
		risknums = risknums + 1
	} else if leftrate >= 55 && leftrate <= 59 {
		smallstatus = "重度"
		smallname = "小肠虚寒"
	} else if leftrate >= 60 && leftrate <= 64 {
		smallstatus = "中度"
		smallname = "小肠虚寒"
	} else if leftrate >= 65 && leftrate <= 69 {
		smallstatus = "轻度"
		smallname = "小肠虚寒"
	} else if leftrate >= 70 && leftrate <= 80 {
		smallstatus = "正常"
		smallname = "小肠功能正常"
	} else if leftrate >= 81 && leftrate <= 85 {
		smallstatus = "轻度"
		smallname = "小肠实热"
	} else if leftrate >= 86 && leftrate <= 90 {
		smallstatus = "中度"
		smallname = "小肠实热"
	} else if leftrate >= 91 && leftrate <= 95 {
		smallstatus = "重度"
		smallname = "小肠实热"
	} else if leftrate >= 96 {
		smallstatus = "严重"
		smallname = "小肠实热"
		risknums = risknums + 1
	}

	//大肠 右侧脉搏
	largestatus := "正常"
	largename := "大肠功能正常"
	if rightrate <= 54 {
		largestatus = "严重"
		largename = "大肠虚寒"
		risknums = risknums + 1
	} else if rightrate >= 55 && rightrate <= 59 {
		largestatus = "重度"
		largename = "大肠虚寒"
	} else if rightrate >= 60 && rightrate <= 64 {
		largestatus = "中度"
		largename = "大肠虚寒"
	} else if rightrate >= 65 && rightrate <= 69 {
		largestatus = "轻度"
		largename = "大肠虚寒"
	} else if rightrate >= 70 && rightrate <= 80 {
		largestatus = "正常"
		largename = "大肠功能正常"
	} else if rightrate >= 81 && rightrate <= 85 {
		largestatus = "轻度"
		largename = "大肠湿热"
	} else if rightrate >= 86 && rightrate <= 90 {
		largestatus = "中度"
		largename = "大肠湿热"
	} else if rightrate >= 91 && rightrate <= 95 {
		largestatus = "重度"
		largename = "大肠湿热"
	} else if rightrate >= 96 {
		largestatus = "严重"
		largename = "大肠湿热"
		risknums = risknums + 1
	}

	//膀胱功能 做出的低压
	bladderstatus := "正常"
	bladdername := "膀胱功能正常"
	if leftlowpre <= 54 {
		bladderstatus = "严重"
		bladdername = "膀胱虚寒"
		risknums = risknums + 1
	} else if leftlowpre >= 55 && leftlowpre <= 59 {
		bladderstatus = "重度"
		bladdername = "膀胱虚寒"
	} else if leftlowpre >= 60 && leftlowpre <= 64 {
		bladderstatus = "中度"
		bladdername = "膀胱虚寒"
	} else if leftlowpre >= 65 && leftlowpre <= 69 {
		bladderstatus = "轻度"
		bladdername = "膀胱虚寒"
	} else if leftlowpre >= 70 && leftlowpre <= 80 {
		bladderstatus = "正常"
		bladdername = "膀胱功能正常"
	} else if leftlowpre >= 81 && leftlowpre <= 85 {
		bladderstatus = "轻度"
		bladdername = "膀胱湿热"
	} else if leftlowpre >= 86 && leftlowpre <= 90 {
		bladderstatus = "中度"
		bladdername = "膀胱湿热"
	} else if leftlowpre >= 91 && leftlowpre <= 95 {
		bladderstatus = "重度"
		bladdername = "膀胱湿热"
	} else if leftlowpre >= 96 {
		bladderstatus = "严重"
		bladdername = "膀胱湿热"
		risknums = risknums + 1
	}

	liufu := UserLiufu{Uid: uid, Pid: pid, Title: "六腑", Gallstatus: gallstatus, Gallname: gallname, Stomachstatus: stomachstatus, Stomachname: stomachname, Smallstatus: smallstatus,
		Smallname: smallname, Largestatus: largestatus, Largename: largename, Bladderstatus: bladderstatus, Bladdername: bladdername, Addtime: time.Now().Unix(), Risknums: risknums}

	err := tx.Table("hr_wx_liufu").Create(&liufu).Error
	if err != nil {
		return err, 0
	}
	return nil, liufu.Id
}

// Tizhi  数字脉诊数据生成 体质分析
func (f *Tizhi) Tizhi(c *gin.Context, tx *gorm.DB, pid, uid, leftrate, leftlowpre, lefthightpre, rightrate, rightlowpre, righthightpre int) (error, *Tizhi) {
	//心脏功能/体质分析 左侧低压
	constitution := "正常"
	constitutioname := "心脏功能正常"
	risknums := 0
	if leftlowpre <= 54 {
		constitution = "严重"
		constitutioname = "阳虚体质"
		risknums = risknums + 1
	} else if leftlowpre >= 55 && leftlowpre <= 59 {
		constitution = "重度"
		constitutioname = "阳虚体质"
	} else if leftlowpre >= 60 && leftlowpre <= 64 {
		constitution = "中度"
		constitutioname = "阳虚体质"
	} else if leftlowpre >= 65 && leftlowpre <= 69 {
		constitution = "轻度"
		constitutioname = "阳虚体质"
	} else if leftlowpre >= 70 && leftlowpre <= 80 {
		constitution = "正常"
		constitutioname = "阴阳平衡"
	} else if leftlowpre >= 81 && leftlowpre <= 85 {
		constitution = "轻度"
		constitutioname = "阴虚体质"
	} else if leftlowpre >= 86 && leftlowpre <= 90 {
		constitution = "中度"
		constitutioname = "阴虚体质"
	} else if leftlowpre >= 91 && leftlowpre <= 95 {
		constitution = "重度"
		constitutioname = "阴虚体质"
	} else if leftlowpre >= 96 {
		constitution = "严重"
		constitutioname = "阴虚体质"
		risknums = risknums + 1
	}
	tizhi := Tizhi{Uid: uid, Pid: pid, Constitution: constitution, Constitutioname: constitutioname, Addtime: time.Now().Unix(), Risknums: risknums, Title: "体质分析"}

	err := tx.Table("hr_wx_tizhi").Create(&tizhi).Error
	if err != nil {
		return err, nil
	}
	return nil, &tizhi
}

// Dabing 大病预警
func (f *Dabing) Dabing(c *gin.Context, tx *gorm.DB, pid, uid, leftrate, leftlowpre, lefthightpre, rightrate, rightlowpre, righthightpre int) (error, *Dabing) {
	var apolexy, apolexy_r int
	apoplexy := "无风险"
	risknums := 0
	/*中风预警算法*/
	if leftlowpre >= rightlowpre {
		apolexy = leftlowpre - rightlowpre
	} else {
		apolexy = rightlowpre - leftlowpre
	}
	if lefthightpre >= righthightpre {
		apolexy_r = lefthightpre - righthightpre
	} else {
		apolexy_r = righthightpre - lefthightpre
	}
	a := leftlowpre - rightlowpre
	b := righthightpre - lefthightpre
	if (a < 0 && b < 0) || (a > 0 && b > 0) {
		if apolexy > apolexy_r {
			if apolexy_r >= 6 && apolexy_r <= 10 {
				apoplexy = "轻度"
			}
		} else if apolexy_r >= 11 && apolexy_r <= 15 {
			apoplexy = "中度"
		} else if apolexy_r >= 16 && apolexy_r <= 20 {
			apoplexy = "重度"
		} else if apolexy_r >= 21 {
			apoplexy = "严重"
			risknums = risknums + 1
		}
	} else {
		if apolexy >= 6 && apolexy <= 10 {
			apoplexy = "轻度"
		} else if apolexy >= 11 && apolexy <= 15 {
			apoplexy = "中度"
		} else if apolexy >= 16 && apolexy <= 20 {
			apoplexy = "重度"
		} else if apolexy >= 21 {
			apoplexy = "严重"
			risknums = risknums + 1
		}
	}
	/*心脏病算法*/
	var heart int
	heart_mess := "无风险"
	if leftrate >= rightrate {
		heart = -rightrate
	} else {
		heart = rightrate - leftrate
	}
	if heart >= 6 && heart <= 10 {
		heart_mess = "轻度"
	} else if heart >= 11 && heart <= 15 {
		heart_mess = "中度"
	} else if heart >= 16 && heart <= 20 {
		heart_mess = "重度"
	} else if heart >= 21 {
		heart_mess = "严重"
		risknums = risknums + 1
	} else if leftrate <= 44 {
		heart_mess = "严重"
		risknums = risknums + 1
	} else if leftrate >= 45 && leftrate <= 49 {
		heart_mess = "重度"
	} else if leftrate >= 50 && leftrate <= 54 {
		heart_mess = "中度"
	} else if leftrate >= 55 && leftrate <= 59 {
		heart_mess = "轻度"
	} else if leftrate >= 60 && leftrate <= 90 {
		heart_mess = "无风险"
	} else if leftrate >= 91 && leftrate <= 95 {
		heart_mess = "轻度"
	} else if leftrate >= 96 && leftrate <= 100 {
		heart_mess = "中度"
	} else if leftrate >= 101 && leftrate <= 105 {
		heart_mess = "重度"
	} else if leftrate >= 106 {
		heart_mess = "严重"
		risknums = risknums + 1
	}
	/*肿瘤算法*/
	tumour := "无风险"
	if lefthightpre > righthightpre {
		if (lefthightpre >= 121 && lefthightpre <= 130) || (righthightpre >= 121 && righthightpre <= 130) {
			tumour = "轻度"
		} else if (lefthightpre >= 131 && lefthightpre <= 140) || (righthightpre >= 131 && righthightpre <= 140) {
			tumour = "中度"
		} else if (lefthightpre >= 141 && lefthightpre <= 150) || (righthightpre >= 141 && righthightpre <= 150) {
			tumour = "重度"
		} else if lefthightpre >= 151 || righthightpre >= 151 {
			tumour = "严重"
			risknums = risknums + 1
		}
	}
	dabing := Dabing{Uid: uid, Pid: pid, Apoplexy: apoplexy, Heart: heart_mess, Tumour: tumour, Addtime: time.Now().Unix(), Risknums: risknums, Title: "大病预警"}

	err := tx.Table("hr_wx_dabing").Create(&dabing).Error
	if err != nil {
		return err, nil
	}
	return nil, &dabing
}
